<!--
 * @Author: 赵京涛 z19472333952022@163.com
 * @Date: 2024-09-29 10:12:02
 * @LastEditors: 赵京涛 z19472333952022@163.com
 * @LastEditTime: 2024-09-29 10:12:02
 * @projectName: HeBeiHaiYangData
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki
-->
<template>
  <el-menu
    :default-active="activeMenu"
    mode="horizontal"
    unique-opened
    @select="handleSelect"
    menu-trigger="click"
  >
    <!-- 顶部菜单超出数量折叠 -->
    <template v-for="(items, index) in topMenus">
      <template v-if="items.children && items.name !== 'systemManagement'">
        <el-submenu :style="{'--theme': theme}" :index="items.path" popper-class="elSubmenuCodeBox">
          <template slot="title">{{ items.meta.title }}</template>
          <template v-for="(item, index) in items.children">
            <el-menu-item
              :index="item.path"
              :key="index">
              {{ item.meta.title }}
            </el-menu-item>
          </template>
        </el-submenu>
      </template>
      <template v-else>
        <el-menu-item :style="{'--theme': theme}" :index="items.path" :key="index" v-if="items.meta || (items.meta.icon && items.meta.icon !== '#')">
          {{ items.meta.title }}
        </el-menu-item>
      </template>
    </template>
  </el-menu>
</template>
<script>
import { constantRoutes } from '@/router'
import { useLocalStorage, warningMessage } from '@/hooks'
// 隐藏侧边栏路由
const hideList = ['/index', '/user/profile'];
export default {
  inject: ['layout'],
  data() {
    return {
      // 顶部栏初始数
      visibleNumber: 5,
      // 当前激活菜单的 index
      currentIndex: undefined
    };
  },
  watch: {
    '$route': {
      handler(to) {
        if(to) {
          if(to.matched && to.matched.length > 1 && to.matched[0].path && to.matched[1].path) {
            const matchedArr = [to.matched[0].path, to.matched[1].path]
            if(to.matched[0].path !== '/systemManagement') {
              this.activeRoutes(matchedArr);
            } else {
              this.activeSystemRoutes(to.matched[0].path);
            }
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = [];
      this.routers.map((menu) => {
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
            topMenus.push(menu.children[0]);
          } else {
            topMenus.push(menu);
          }
        }
      });
      return topMenus;
    },
    // 所有的路由信息
    routers() {
      return this.$store.state['permission'].topbarRouters;
    },
    // 设置子路由
    childrenMenus() {
      const childrenMenus = []
      this.routers.map((router) => {
        for (const item in router.children) {
          if (router.children[item].parentPath === undefined) {
            if(router.path === "/") {
              router.children[item].path = "/" + router.children[item].path;
            } else {
              if(!this.ishttp(router.children[item].path)) {
                router.children[item].path = router.path + "/" + router.children[item].path;
              }
            }
            router.children[item].parentPath = router.path;
          }
          childrenMenus.push(router.children[item]);
        }
      });
      return constantRoutes.concat(childrenMenus);
    },
    // 默认激活的菜单
    activeMenu() {
      const path = this.$route.path;
      let activePath = path;
      if (path !== undefined && path.lastIndexOf("/") > 0 && hideList.indexOf(path) === -1) {
        const tmpPath = path.substring(1, path.length);
        let parts = [];
        let slashCount = 0;
        for (let i = 0; i < tmpPath.length; i++) {
          if (tmpPath[i] === '/') {
            slashCount++;
            if (slashCount === 2) break; // 找到第二个'/'时退出循环
          }
          parts.push(tmpPath[i]);
        }
        let result = parts.join(''); // 将数组转换回字符串
        activePath = "/" + result;
        if (!this.$route.meta.link) {
          this.$store.dispatch('app/toggleSideBarHide', false);
        }
      } else if(!this.$route['children']) {
        activePath = path;
        this.$store.dispatch('app/toggleSideBarHide', false);
      }
      if(activePath.includes('systemManagement')) {
        return '/systemManagement'
      } else {
        return activePath;
      }
    },
  },
  beforeMount() {
    window.addEventListener('resize', this.setVisibleNumber)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setVisibleNumber)
  },
  mounted() {
    this.setVisibleNumber();
  },
  methods: {
    // 根据宽度计算设置显示栏数
    setVisibleNumber() {
      const width = document.body.getBoundingClientRect().width / 3;
      this.visibleNumber = parseInt(width / 85);
    },
    // 菜单选择事件
    handleSelect(key, keyPath) {
      if(['/gisMap', '/marineEcology'].includes(key)) return
      if(['/beidaiheSpecial'].includes(key)) {
        window.open('http://lc.guo.lol:28080/HeBeiHaiYangSJPJ/#/login', "_blank")
        return
      }
      this.currentIndex = key;
      const route = this.routers.find(item => item.path === keyPath[0]);
      if (this.ishttp(key)) {
        // http(s):// 路径新窗口打开
        window.open(key, "_blank");
      } else if (!route || !route.children) {
        // 没有子路由路径内部打开
        const routeMenu = this.childrenMenus.find(item => item.path === key);
        if (routeMenu && routeMenu.query) {
          let query = JSON.parse(routeMenu.query);
          this.$router.push({ path: key, query: query });
        } else {
          this.$router.push({ path: key });
        }
        this.$store.dispatch('app/toggleSideBarHide', false);
      } else {
        // 显示左侧联动菜单
        if(key !== '/systemManagement') {
          this.activeRoutes(keyPath);
        } else {
          this.activeSystemRoutes(key);
        }
        this.$store.dispatch('app/toggleSideBarHide', false);
      }
    },
    // 当前激活的路由
    activeRoutes(keyPath) {
      let routes = []
      if (this.childrenMenus && this.childrenMenus.length > 0) {
        this.childrenMenus.map((item) => {
          if (keyPath[0] === item.parentPath) {
            if(item && item.path === keyPath[1]) {
              if(item.children && item.children.length > 0) {
                item.children.forEach((child) => {
                  child.parentPath = keyPath[1]
                })
                routes = item.children
              } else {
                warningMessage('暂无此页面内容')
              }
            }
          }
        });
      }
      if(routes.length > 0) {
        useLocalStorage.setItem('sidebarRouters', JSON.stringify(routes));
        this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      } else {
        this.$store.dispatch('app/toggleSideBarHide', false);
      }
    },
    // 激活系统管理菜单路由
    activeSystemRoutes(key) {
      let routes = []
      if (this.childrenMenus && this.childrenMenus.length > 0) {
        this.childrenMenus.map((item) => {
          if (key === item.parentPath) {
            routes.push(item)
          }
        });
      }
      if(routes.length > 0) {
        useLocalStorage.setItem('sidebarRouters', JSON.stringify(routes));
        this.$store.commit("SET_SIDEBAR_ROUTERS", routes);
      } else {
        this.$store.dispatch('app/toggleSideBarHide', false);
      }
    },
    ishttp(url) {
      return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1
    }
  },
};
</script>
